﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Configuration;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections;
using System.Reflection;
using AjaxControlToolkit;
using System.Security.Cryptography;
using System.Runtime.Serialization.Json;
using System.IO;
using Telerik.Web.UI;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for SDS_Util
/// </summary>

public class Util
{   
    public static void clearPanel(ref Panel pn){
        Control[] csn = GenDataTable.GetControlFrom(pn);
        string strValue = "";
        for (int i = 0; i < csn.Length; i++)
        {
            Type ty = csn[i].GetType();
            if (ty == typeof(Label))
            { ((Label)csn[i]).Text = strValue; }
            else if (ty == typeof(TextBox))
            {
                ((TextBox)csn[i]).Text = strValue;
            }
            else if (ty == typeof(DropDownList))
            {
                if (((DropDownList)csn[i]).Items.Count > 0) ((DropDownList)csn[i]).SelectedIndex = 0;
            }
            else if (ty == typeof(RadioButton))
            {
                ((RadioButton)csn[i]).Checked = false;
            }
            else if (ty == typeof(CheckBox))
            {
                ((CheckBox)csn[i]).Checked = false;

            }
            else if (ty == typeof(RadComboBox))
            {
                ((RadComboBox)csn[i]).SelectedIndex = 0;

            }
            else if (ty == typeof(RadTextBox))
            {
                ((RadTextBox)csn[i]).Text = "";

            }
            else if (ty == typeof(RadNumericTextBox))
            {
                ((RadNumericTextBox)csn[i]).Text = "";

            }
            else if (ty == typeof(RadDatePicker))
            {
                ((RadDatePicker)csn[i]).SelectedDate = null;

            }
        }
    }
    public static SqlDataSource GetDataSource(string command)
    {
        SqlDataSource dataSource = new SqlDataSource();
        dataSource.SelectCommandType = SqlDataSourceCommandType.Text;
        dataSource.SelectCommand = command;
        dataSource.ConnectionString = ConfigurationManager.AppSettings["Main.ConnectionString"]; 
        return dataSource;
    }
    public static DataTable GetDataTable(string command){
        if (command.IndexOf("insert") > -1 || command.IndexOf("update") > -1 || command.IndexOf("delete") > -1 ||
            command.IndexOf("insert".ToUpper()) > -1 || command.IndexOf("update".ToUpper()) > -1 || command.IndexOf("delete".ToUpper()) > -1) 
        {
            throw new Exception(String.Format("SQL Injection Error Command : {0}",command));
        }
        SqlDataSource sql = Util.GetDataSource(command);
        DataSourceSelectArguments dssa = new DataSourceSelectArguments();
        dssa.AddSupportedCapabilities(DataSourceCapabilities.RetrieveTotalRowCount);
        dssa.RetrieveTotalRowCount = true;
        DataView dv = (DataView)sql.Select(dssa);
        return dv.Table;
    }
    public static void jsPopup(UpdatePanel udpn, string url)
    {
        jsWriter(udpn, "openPopup" + (new Random()).Next(), "window.open(\"" + url + "\");");
    }
    public static void jsPopup(Page p, string url)
    {
        jsWriter(p, "openPopup" + (new Random()).Next(), "window.open(\"" + url + "\");");
    }

    public static void jsPopup(Page p, string url,string properties,string windowsVarName) {

        jsWriter(p, "openPopup" + (new Random()).Next(), windowsVarName+"=window.open(\"" + url + "\",\"mywindow\",\"" + properties + "\");");
    
    }
    public static void jsPopup(UpdatePanel udpn, string url,int width,int height)
    {
        jsWriter(udpn, "openPopup" + (new Random()).Next(), "window.open(\"" + url + "\");");
    }
    public static void jsPopup(Page p, string url, int width, int height)
    {
        jsWriter(p, "openPopup" + (new Random()).Next(), "window.open(\"" + url + "\");");
    }
   
    public static void jsConsole(UserControl uct, string msg)
    {

        jsWriter(uct, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "console.log(" + EncodeJsString(msg) + "); ");
    }
    public static void jsConsole(UserControl uct, Exception exc)
    {

        jsWriter(uct, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "console.log(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsConsole(Page pg, Exception exc)
    {
        jsWriter(pg, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "console.log(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsConsole(Page pg, string msg)
    {
        jsWriter(pg, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_"+(new Random()).Next(), "console.log(" + EncodeJsString(msg) + "); ");
    }
    public static void jsConsole(UpdatePanel pg, string msg)
    {
        jsWriter(pg, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "console.log(" + EncodeJsString(msg) + "); ");
    }
    public static void jsConsole(UpdatePanel udpn, Exception exc)
    {
        jsWriter(udpn, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "console.log(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsConsole(MasterPage mtp, Exception exc)
    {
        jsWriter(mtp, "console_log_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "console.log(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsAlert(UserControl uct, Exception exc)
    {
        jsWriter(uct, "alert_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "alert(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsAlert(UpdatePanel udpn, Exception exc)
    {
        jsWriter(udpn, "alert_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "alert(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsAlert(Page pg, Exception exc)
    {
        jsWriter(pg, "alert_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "alert(" + EncodeJsString(exc.Message) + "); ");
    }
    public static void jsAlert(UserControl uct, string p1)
    {
        jsWriter(uct, "alert_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "alert(" + EncodeJsString(p1) + "); ");
    }
    public static void jsAlert(UpdatePanel udpn, string p1)
    {
        jsWriter(udpn, "alert_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "alert(" + EncodeJsString(p1) + "); ");
    }
    public static void jsAlert(Page pg, string p1)
    {
        jsWriter(pg, "alert_script" + DateTime.Now.Millisecond.ToString() + "_" + (new Random()).Next(), "alert(" + EncodeJsString(p1) + "); ");
    }
    public static void jsRedirect(UpdatePanel udpn, string url)
    {
        jsWriter(udpn, "redirect", "document.location=\"" + url + "\"; ");

    }
    public static void jsRedirect(Page pg, string url)
    {
        jsWriter(pg, "redirect", "document.location=\"" + url + "\"; ");

    }
    public static void jsRedirect(MasterPage mp, string url)
    {
        jsWriter(mp, "redirect", "document.location=\"" + url + "\"; ");
    }
    public static void jsWriter(UpdatePanel udpn, string p1, string p2)
    {
        ScriptManager.RegisterStartupScript(udpn, udpn.GetType(), p1, p2, true);
    }
    public static void jsWriter(UserControl uct, string p1, string p2)
    {
        ScriptManager.RegisterStartupScript(uct, uct.GetType(), p1, p2, true);
    }
    public static void jsWriter(Page pg,string p2)
    {
        if (pg == null) return;
        ScriptManager.RegisterStartupScript(pg, pg.GetType(), RandomString(4), p2, true);
    }
    public static void jsWriter(Page pg, string p1, string p2)
    {
        if (pg == null) return;
        ScriptManager.RegisterStartupScript(pg, pg.GetType(), p1, p2, true);
    }
    private static string RandomString(int size)
    {
        Random random = new Random((int)DateTime.Now.Ticks);
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }

        return builder.ToString();
    }
    public static void jsWriter(MasterPage mp, string p1, string p2)
    {
        ScriptManager.RegisterStartupScript(mp, mp.GetType(), p1, p2, true);
    }
    public static string EncodeJsString(string s)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("\"");
        foreach (char c in s)
        {
            switch (c)
            {
                case '\"':
                    sb.Append("\\\"");
                    break;
                case '\\':
                    sb.Append("\\\\");
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                default:
                    int i = (int)c;
                    if (i < 32 || i > 127)
                    {
                        sb.AppendFormat("\\u{0:X04}", i);
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;
            }
        }
        sb.Append("\"");

        return sb.ToString();
    }
    public static void FillInFormTo(object spDatain, Control[] fm, bool SaveMode)
    {
        if (spDatain == null) { return; }
        object spData = null;
        if (spDatain is Array)
        {
            
        }
        else { spData = spDatain; }
        Control[] fmControl = fm;
        atmGen.PropByName DBByName = new atmGen.PropByName(spData);
        string msg = "";
        int cnt = fmControl.Length;
        if (SaveMode)
        {
            for (int i = 0; i < cnt; ++i)
            {
                if (fmControl[i] is Button) { continue; }
                string id = fmControl[i].ID;

                if (id == "RD_COUNTY_NO")
                {
                    msg += (id + " , "); 
                }

                string dbFiels = id.Substring(id.IndexOf('_') + 1);
                try
                {
                    DBByName.SetValue(dbFiels, atmGen.atmData.getFormValue(fmControl[i]));
                }
                catch (Exception ex) 
                { 
                    msg += (id + " , "); 
                }
            }
        }
        else
        {
            for (int i = 0; i < cnt; ++i)
            {
                string id = fmControl[i].ID;
                id = id.Substring(id.IndexOf('_') + 1);


                if (fmControl[i] is RadButton) //fmControl[i] is Button)
                {
                    if (((RadButton)fmControl[i]).ToggleType != ButtonToggleType.CustomToggle)
                        continue;
                }

                if (fmControl[i] is Button) 
                {
                    continue;
                }

                try
                {
                    if (id == "InstallDate")
                    {
                        string txt = "";

                        try
                        {
                            txt = Convert.ToDateTime(DBByName.GetValue(id)).ToString();
                        }
                        catch { }
                        atmGen.atmData.setFormValue(fmControl[i], txt);
                    }
                    else
                    {

                        string txt = DBByName.GetValue(id).ToString();
                        if (DBByName.GetValue(id) is DateTime) 
                        {
                            txt = ((DateTime)DBByName.GetValue(id)).ToString("dd/MM/yyyy");
                        }
                        atmGen.atmData.setFormValue(fmControl[i], txt);
                    }
                }
                catch (Exception ex) { msg += (id + " , "); }
            }
        }

    }

    public static string formatnumber(object value, int showType)
    {
        if (showType == 1)
        {
            try
            {
                string f = String.Format("{0:F2}", value);
            }
            catch { }
        }
        else if (showType == 2)
        {
            try
            {
                string f = String.Format("{0:#,###.00}", Convert.ToDecimal(value));


                return (f.IndexOf('.') == 0) ? "0" + f : f;
            }

            catch { }
        }
        else if (showType == 3)
        {
            try
            {
                return getNumberCommas(value);
            }
            catch { }
        }
        else if (showType == 4)
        {
            try
            {
                return cleanCommar(value);
            }
            catch { }
        }
        else if (showType == 5)
        {
            try
            {
                return String.Format("{0:c}", value);

            }
            catch { }
            //c 	Currency 	{0:c} 	$1.42 	-$12,400

        }
        else if (showType == 6)
        {
            try
            {
                return String.Format("{0:d}", value);

            }
            catch { }
            //     d 	Decimal (Whole number) 	 	System.FormatException 	-12400

        }
        else if (showType == 7)
        {

            //    e 	Scientific 	{0:e} 	1.420000e+000 	-1.240000e+004

            try
            {
                return String.Format("{0:e}", value);

            }
            catch { }
            //f 	Fixed point 	{0:f} 	1.42 	-12400.00
            //g 	General 	{0:g} 	1.42 	-12400
            //n 	Number with commas for thousands 	{0:n} 	1.42 	-12,400
            //r 	Round trippable 	{0:r} 	1.42 	System.FormatException
            //x 	Hexadecimal 	{0:x4} 	System.FormatException 	cf90
        }
        else if (showType == 8)
        {
            try
            {

                return String.Format("{0:#,###}", Convert.ToDecimal(value));

            }
            catch { return value.ToString(); }


        }

        return value.ToString();
    }
    public static string getNumberCommas(object res)
    {
        string[] result;
        if (res.ToString().IndexOf(',') > 1)
        {
            res = cleanCommar(res.ToString());
        }
        string s_inum = res.ToString();
        string[] num2 = s_inum.Split('.');
        int l_inum = 0;

        l_inum = num2[0].Length;


        string n_inum = "";
        for (int i = 0; i < l_inum; i++)
        {
            if ((l_inum - i) % 3 == 0)
            {
                if (i == 0)
                {
                    n_inum += CharAt(s_inum, i);
                }
                else
                {
                    n_inum += "," + CharAt(s_inum, i);
                }
            }
            else
            {
                n_inum += CharAt(s_inum, i);
            }
        }
        if (num2.Length > 1)
        {
            n_inum += "." + num2[1];
        }

        return n_inum;
    }
    public static string cleanCommar(object res)
    {
        return res.ToString().Replace(",", "");
    }
    public static char CharAt(string strText, int index)
    {
        char[] charAt = strText.ToCharArray();
        return charAt[index];
    }
    public static string GetControlsNameForPanel(Panel pn)
    {
        return GetControlNameFrom(GetControlFrom(pn));
    }
    public static string GetDummyForPanel(Panel pn)
    {
        return GetDataTableDummy(GetControlFrom(pn));
    }

    public static Type[] SupportControls() 
    {
        return new Type[] { typeof(TextBox), typeof(DropDownList), typeof(RadioButton),
        typeof(CheckBox),typeof(RadComboBox),typeof(RadTextBox),typeof(RadNumericTextBox),typeof(RadDatePicker),typeof(Label)};
    }

    public static bool IsSupportType(Control c) 
    {
        foreach (Type type in SupportControls()) 
        {
            if(c.GetType() ==  type)
            {
                return true;
            }
        }

        return false;
    }

    public static Control[] GetControlFromHtmlTableRow(HtmlTableRow c) 
    {
        List<Control> cn = new List<Control>();
        for (int i = 0; i < c.Controls.Count; i++) 
        {
            if (c.Controls[i] is HtmlTableCell)
            {
                if(((HtmlTableCell)c.Controls[i]).Controls.Count>0){
                    foreach (Control r in ((HtmlTableCell)c.Controls[i]).Controls) 
                    {
                        if (IsSupportType(r))
                        {
                            cn.Add(r);
                        }
                    }
                }
            }
        }

        return cn.ToArray();
    }

    public static void DisableControlAndVisbledButton(Control[] controls) 
    {
        foreach (Control c in controls) 
        {
            if(c is Button || c is RadButton)
            {
                c.Visible = false;
                continue;
            }

            if(c is TextBox)
            {
                ((TextBox)c).Enabled = false;
                continue;
            }

            if (c is RadTextBox)
            {
                ((RadTextBox)c).Enabled = false;
                continue;
            }

            if (c is RadDatePicker)
            {
                ((RadDatePicker)c).Enabled = false;
                continue;
            }
        }
    }

    public static Control[] GetControlFrom(Panel pn)
    {
        List<Control> listControls = new List<Control>();
        foreach (Control c in pn.Controls)
        {
            //If ignore control was visibled.
            if (!c.Visible) { continue; }
            if (c.ID != null)
            {
                if (c is Panel)
                {
                    Control[] cn = GetControlFrom((Panel)c);
                    foreach (Control cx in cn)
                    {
                        listControls.Add(cx);
                    }
                }
                else if (c is HtmlTableRow)
                {
                    Control[] cn = GetControlFromHtmlTableRow((HtmlTableRow)c);
                    foreach (Control cx in cn)
                    {
                        listControls.Add(cx);
                    }
                }
                else if (c is UpdatePanel)
                {

                    UpdatePanel ctrlPanel = (UpdatePanel)c;
                    if (ctrlPanel.HasControls())
                    {

                        foreach (Control subCtrl in ctrlPanel.Controls[0].Controls)
                        {
                            if (subCtrl is LiteralControl)
                                continue;
                            else if (subCtrl is Panel)
                            {
                                Control[] cn = GetControlFrom((UpdatePanel)c);
                                foreach (Control cx in cn)
                                {
                                    listControls.Add(cx);
                                }
                            }
                            else
                                listControls.Add(subCtrl);
                        }
                    }

                }
                else
                    listControls.Add(c);
            }

        }
        return (Control[])listControls.ToArray();
    }
    public static Control[] GetControlFrom(UpdatePanel pn)
    {
        List<Control> listControls = new List<Control>();
        foreach (Control c in pn.Controls)
        {
            if (c.ID != null)
            {
                if (c is UpdatePanel)
                {
                    Control[] cn = GetControlFrom((UpdatePanel)c);
                    foreach (Control cx in cn)
                    {
                        listControls.Add(cx);
                    }
                }
                else
                    listControls.Add(c);
            }

        }
        return (Control[])listControls.ToArray();
    }
    public static string GetControlNameFrom(Control[] pn)
    {
        ArrayList str = new ArrayList();
        DataTable newDataTable = new DataTable();
        DataRow newDataRows = newDataTable.NewRow();
        string textSt = "";
        textSt += @"DataTable newDataTable = new DataTable();";
        textSt += " ";
        foreach (Control c in pn)
        {
            if (c.GetType() == typeof(ImageButton) || GetStringFindControlValue(c) == "")
            {
                continue;
            }
            textSt += "newDataTable.Columns.Add(\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\");";
            textSt += " ";
        }
        //string[] newStr = (string[])str.ToArray();


        textSt += "DataRow newDataRows = newDataTable.NewRow();";
        textSt += " ";
        foreach (Control c in pn)
        {
            if (c.GetType() == typeof(ImageButton) || GetStringFindControlValue(c) == "")
            {
                continue;
            }
            textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = " + GetStringFindControlValue(c) + ";";
            textSt += " ";
        }
        textSt += "newDataTable.Rows.Add(newDataRows);";
        return textSt;
        //MsgBox(textSt);
    }

    public static string GetDummyFromPanel(Control[] pn)
    {
        ArrayList str = new ArrayList();
        DataTable newDataTable = new DataTable();
        DataRow newDataRows = newDataTable.NewRow();
        string textSt = "";
        textSt += @"DataTable newDataTable = new DataTable();";
        textSt += " ";
        foreach (Control c in pn)
        {
            if (c.GetType() == typeof(ImageButton) || GetStringFindControlValue(c) == "")
            {
                continue;
            }
            textSt += "newDataTable.Columns.Add(\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\");";
            textSt += " ";
        }
        //string[] newStr = (string[])str.ToArray();


        textSt += "DataRow newDataRows = newDataTable.NewRow();";
        textSt += " ";
        int i = 0;
        foreach (Control c in pn)
        {
            if (c.GetType() == typeof(ImageButton) || GetStringFindControlValue(c) == "")
            {
                continue;
            }
            textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = " + i + ";";
            textSt += " ";
            i++;
        }
        textSt += "newDataTable.Rows.Add(newDataRows);";
        return textSt;
        //MsgBox(textSt);
    }

    public static string GetDataTableDummy(Control[] pn)
    {
        ArrayList str = new ArrayList();
        DataTable newDataTable = new DataTable();
        DataRow newDataRows = newDataTable.NewRow();
        string textSt = "";
        textSt += @"DataTable newDataTable = new DataTable();";
        textSt += " ";
        foreach (Control c in pn)
        {
            if (c.GetType() == typeof(ImageButton) || GetStringFindControlValue(c) == "")
            {
                continue;
            }
            textSt += "newDataTable.Columns.Add(\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\");";
            textSt += " ";
        }
        //string[] newStr = (string[])str.ToArray();


        textSt += "DataRow newDataRows = newDataTable.NewRow();";
        textSt += " ";
        foreach (Control c in pn)
        {
            if (c.GetType() == typeof(ImageButton) || GetStringFindControlValue(c) == "")
            {
                continue;
            }
            if (c.ID.ToLower().IndexOf("id") > -1)
            {
                textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = -1;";
                textSt += " ";
            }
            else if (c.ID.ToLower().IndexOf("chk") > -1)
            {
                textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = false;";
                textSt += " ";
            }
            else if (c.ID.ToLower().IndexOf("text") > -1)
            {
                textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = \"random " + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\";";
                textSt += " ";
            }
            else if (c.ID.ToLower().IndexOf("date") > -1)
            {
                textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = DateTime.Now;";
                textSt += " ";
            }
            else
            {
                textSt += "newDataRows[\"" + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\"] = \"random " + c.ID.Substring(c.ID.IndexOf('_') + 1) + "\";";
                textSt += " ";
            }
        }
        textSt += "newDataTable.Rows.Add(newDataRows);";
        return textSt;
        //MsgBox(textSt);
    }
    public static void MsgBox(string msg)
    {
        HttpContext.Current.Session["alertDataRows"] = msg;
        Page page = HttpContext.Current.Handler as Page;
        if (page != null)
        {

            Util.jsWriter(page, "rwrwr", "window.open('Default2.aspx?x='" + new Random(1).Next() + ")");
            //SDS_Util.jsAlert(page, msg);
        }

    }
    public static string GetStringFindControlValue(Control ControlTypeName)
    {

        if (ControlTypeName.GetType() == typeof(TextBox))
        {
            return "((TextBox)" + ControlTypeName.ID + ").Text.Trim()";
        }
        else if (ControlTypeName.GetType() == typeof(CheckBox))
        {
            return "((CheckBox)" + ControlTypeName.ID + ").Checked.ToString()";
        }
        else if (ControlTypeName.GetType() == typeof(RadioButtonList))
        {
            return "((RadioButtonList)" + ControlTypeName.ID + ").SelectedValue.ToString()";
        }
        else if (ControlTypeName.GetType() == typeof(RadioButton))
        {
            return "((RadioButton)" + ControlTypeName.ID + ").Checked.ToString()";
        }
        else if (ControlTypeName.GetType() == typeof(Label))
        {
            return "((Label)" + ControlTypeName.ID + ").Text.ToString()";
        }
        else if (ControlTypeName.GetType() == typeof(DropDownList))
        {
            return "((DropDownList)" + ControlTypeName.ID + ").SelectedValue.ToString()";
        }
        else
        {
            return "";
        }
    }
    public static string FindControlValue(Control ControlTypeName)
    {

        if (ControlTypeName.GetType() == typeof(TextBox))
        {
            return ((TextBox)ControlTypeName).Text.Trim() == "" ? "0" : ((TextBox)ControlTypeName).Text;
        }
        else if (ControlTypeName.GetType() == typeof(CheckBox))
        {
            return ((CheckBox)ControlTypeName).Checked.ToString();
        }
        else if (ControlTypeName.GetType() == typeof(RadioButtonList))
        {
            return ((RadioButtonList)ControlTypeName).SelectedValue.ToString();
        }
        else if (ControlTypeName.GetType() == typeof(RadioButton))
        {
            return ((RadioButton)ControlTypeName).Checked.ToString();
        }
        else
        {
            return null;
        }
    }

    public static void ResetForm(Control[] ctrl) 
    {
        foreach(Control c in ctrl)
        {
            SetFormValue(c, "");
        }
    }


    public static void SetFormValue(object ctrl, object value)
    {
        if (ctrl == null) { return; }
        //if (ctrl.GetType().IsEnum)
        //{
        //    return Convert.ChangeType(ctrl, typeof(Int64)).ToString();
        //}
        //else
        {
            Type ty = ctrl.GetType();
      
            if (ty == typeof(TextBox))
            {
                ((TextBox)ctrl).Text = "";
            }
            else if (ty == typeof(RadTextBox))
            {
                ((RadTextBox)ctrl).Text = "";
            }
            else if (ty == typeof(DropDownList))
            {
                ((DropDownList)ctrl).SelectedIndex = 0;
            }
            else if (ty == typeof(RadComboBox))
            {
                ((RadComboBox)ctrl).SelectedIndex = 0;
            }
            else if (ty == typeof(RadioButton))
            {
                ((RadioButton)ctrl).Checked = false;
            }
            else if (ty == typeof(CheckBox))
            {
                ((CheckBox)ctrl).Checked = false;

            }
            else if (ty == typeof(HiddenField))
            {
                ((HiddenField)ctrl).Value = "";

            }
            else if (ty == typeof(RadDatePicker))
            {
                ((RadDatePicker)ctrl).SelectedDate = null;
            }
            else if (ty == typeof(Button))
            {
                return;
            }
            else
            {

            }
        }
    }

    public static Control[] GetControlFrom(Content pn)
    {
        List<Control> listControls = new List<Control>();
        foreach (Control c in pn.Controls)
        {
            if (c.ID != null)
            {
                if (c is Panel)
                {
                    Control[] cn = GetControlFrom((Panel)c);
                    foreach (Control cx in cn)
                    {
                        listControls.Add(cx);
                    }
                }
                else
                    listControls.Add(c);
            }

        }
        return (Control[])listControls.ToArray();
    }
    public static string WriteDummy(Object obj, string objName)
    {
        Type t = obj.GetType();
        PropertyInfo[] pi = t.GetProperties();
        string text = "";
        Random rd = new Random();
        foreach (PropertyInfo p in pi)
        {
            if (p.PropertyType.FullName.IndexOf("Int") > 1)
            {
                text += objName + "." + p.Name + " = " + "-1;" + "</br>";
            }
            else if (p.PropertyType.FullName.IndexOf("String") > 1)
            {
                text += objName + "." + p.Name + " = " + "\"" + rd.Next() + "\";" + "</br>";
            }
            else if (p.PropertyType.FullName.IndexOf("Boolean") > 1)
            {
                text += objName + "." + p.Name + " = " + "false;" + "</br>";
            }
            else if (p.PropertyType.FullName.IndexOf("DateTime") > 1)
            {
                text += objName + "." + p.Name + " = " + "DateTime.Now;" + "</br>";
            }
        }
        return text;
    }
    public static bool IsBlank(Object obj) 
    {
        if (obj == null || obj.ToString().Trim()=="")
        {
            return true;
        }
        else 
        {
            return false;
        }
    }
    public static string ToJSon(Object obj)
    {
        string sJSON = "";
        try
        {
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
             new System.Web.Script.Serialization.JavaScriptSerializer();
            sJSON = oSerializer.Serialize(obj);
        }
        catch { }
        return sJSON;
    }
    public static string ToString(int? a) 
    {
        return a!=null?(a+""):null;
    }
    public static Decimal? StringToDecimal(object strg)
    {
        try
        {
            return Decimal.Parse(strg.ToString());
        }
        catch {
            return null;
        }
    }
    public static decimal? StringTodecimal(object strg)
    {
        try
        {
            return decimal.Parse(strg.ToString());
        }
        catch
        {
            return null;
        }
    }
    public static int? StringToInt(object strg)
    {
        try
        {
            return int.Parse(strg.ToString());
        }
        catch
        {
            return null;
        }
    }

    public static string ToString(object p)
    {
        if(p!=null){
            return p.ToString();
        }return null;
    }
    public static string EncryptString(string Message)
    {
        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

        // Step 1. We hash the passphrase using MD5
        // We use the MD5 hash generator as the result is a 128 bit byte array
        // which is a valid length for the TripleDES encoder we use below

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes("ect"));

        // Step 2. Create a new TripleDESCryptoServiceProvider object
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        // Step 3. Setup the encoder
        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;

        // Step 4. Convert the input string to a byte[]
        byte[] DataToEncrypt = UTF8.GetBytes(Message);

        // Step 5. Attempt to encrypt the string
        try
        {
            ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
            Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
        }
        finally
        {
            // Clear the TripleDes and Hashprovider services of any sensitive information
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }

        // Step 6. Return the encrypted string as a base64 encoded string
        return Convert.ToBase64String(Results);
    }

    public static string DecryptString(string Message)
    {
        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

        // Step 1. We hash the passphrase using MD5
        // We use the MD5 hash generator as the result is a 128 bit byte array
        // which is a valid length for the TripleDES encoder we use below

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes("ect"));

        // Step 2. Create a new TripleDESCryptoServiceProvider object
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        // Step 3. Setup the decoder
        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;

        // Step 4. Convert the input string to a byte[]
        byte[] DataToDecrypt = Convert.FromBase64String(Message);

        // Step 5. Attempt to decrypt the string
        try
        {
            ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
            Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
        }
        finally
        {
            // Clear the TripleDes and Hashprovider services of any sensitive information
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }

        // Step 6. Return the decrypted string in UTF8 format
        return UTF8.GetString(Results);
    }

    public static string Limit(object Desc, int length)
    {
        StringBuilder strDesc = new StringBuilder();
        strDesc.Insert(0, Desc.ToString());

        if (strDesc.Length > length)
            return strDesc.ToString().Substring(0, length) + "... <img src='images/more.png'>";
        else return strDesc.ToString();
    }


    public static void ClearGridToDefault(ref Telerik.Web.UI.RadGrid RadGrid_Search)
    {
        RadGrid_Search.CurrentPageIndex = 0;
        RadGrid_Search.PageSize = 10;
        RadGrid_Search.VirtualItemCount = 0;
    }
    public static string Serialize<T>(T obj)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        string retVal = Encoding.UTF8.GetString(ms.ToArray());
        return retVal;
    }

    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        return obj;
    }
    public static void CopyObject<T>(object sourceObject, ref T destObject)
    {
        //	If either the source, or destination is null, return
        if (sourceObject == null || destObject == null)
            return;

        //	Get the type of each object
        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        //	Loop through the source properties
        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            //	Get the matching property in the destination object
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            //	If there is none, skip
            if (targetObj == null)
                continue;

            //	Set the value in the destination
            targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
        }
    }

}
public class MsgResult {
   

}